package org.enhance.common.model.po;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import org.apache.commons.collections4.CollectionUtils;
import org.enhance.common.util.Assertion;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class GeoMultiPolygon extends AbstractGeo {

	private static final long serialVersionUID = 1937295214272363107L;

	private List<GeoPolygon> multiPolygons;

	public GeoMultiPolygon addPolygon(GeoPolygon polygon) {
		if (multiPolygons == null) {
			multiPolygons = new ArrayList<>();
		}
		multiPolygons.add(polygon);
		return this;
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) {
			return true;
		}
		if (o == null || getClass() != o.getClass()) {
			return false;
		}
		GeoMultiPolygon that = (GeoMultiPolygon) o;
		return multiPolygons.equals(that.multiPolygons);
	}

	@Override
	public int hashCode() {
		return Objects.hash(multiPolygons);
	}

	@Override
	public String generateShape() {
		if (CollectionUtils.isNotEmpty(multiPolygons)) {
			Assertion.isTrue(isPolygon(), "地块数据有问题，请检查");
			StringBuilder sb = new StringBuilder("MULTIPOLYGON(");
			for (int i = 0; i < multiPolygons.size(); i++) {
				GeoPolygon polygon = multiPolygons.get(i);
				List<GeoPoint> geoPoints = polygon.getGeoPoints();
				sb.append("((");
				for (int j = 0; j < geoPoints.size(); j++) {
					GeoPoint geoPoint = geoPoints.get(j);
					sb.append(geoPoint.getLongitude()).append(" ").append(geoPoint.getLatitude());
					if (geoPoint.getAltitude() != null) {
						sb.append(" ").append(geoPoint.getAltitude());
					}
					if (j != geoPoints.size() - 1) {
						sb.append(",");
					}
				}
				sb.append("))");
				if (i != multiPolygons.size() - 1) {
					sb.append(",");
				}
			}
			sb.append(")");
			return sb.toString();
		}
		return null;
	}

	private boolean isPolygon() {
		for (GeoPolygon multiPolygon : multiPolygons) {
			if (!multiPolygon.isPolygon()) {
				return false;
			}
		}
		return true;
	}
}
